package com.example.cadmin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cadmin.entity.Host;
import com.example.cadmin.entity.MotorLog;
import com.example.cadmin.security.dto.JwtUserDto;
import com.example.cadmin.service.HostService;
import com.example.cadmin.service.MotorLogService;
import com.example.cadmin.utils.DateFormat;
import com.example.cadmin.utils.Netty.sendCmd;
import com.example.cadmin.utils.ResponseModel;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 智能选层柜 手动模式-控制器
 * </p>
 *
 * @author 张彬
 * @since 2022-08-20
 */
@Controller
@RequestMapping("/motor/manual")
public class MotorManualController {
    @Resource
    public FileManageController fileManageController;
    @Resource
    public MotorLogService motorLogService;
    @Resource
    public sendCmd sendCmd;
    @Resource
    public HostService hostService;

    /**
     * 获取机柜编号
     */
    public String getNumber(HttpServletRequest request) {
        return Convert.toStr(request.getSession().getAttribute("number"));
    }

    /**
     * 封装电机运行日志
     *
     * @return
     */
    public void motorLog(int type, String operation, JwtUserDto jwtUserDto, String number) {
        MotorLog motorLog = new MotorLog();
        String userName = jwtUserDto.getMyUser().getUserName();
        Integer userId = jwtUserDto.getMyUser().getUserId();
        motorLog.setUserName(userName);
        motorLog.setUserId(userId);
        motorLog.setType(type);
        motorLog.setCreateTime(DateFormat.getTime());
        motorLog.setOperation(operation);
        motorLog.setNumber(number);
        motorLogService.save(motorLog);
    }

    /**
     * 手动操作页面
     */
    @GetMapping("index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("MotorManual/index");
        List<Map<String, Object>> hostList = hostService.listMaps();
        modelAndView.addObject("hostList", hostList);
        return modelAndView;
    }

    /**
     * rfid开门
     */
    @PostMapping("/open/door")
    @ResponseBody
    public ResponseModel openDoorSave(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("hostId"))) {
            return ResponseModel.fail("请选择柜号");
        }
        Host host = hostService.getById(data.getInt("hostId"));
        // 调用别的柜子接口
        String result = HttpRequest.post(host.getCabinetIp() + "/api/server/openDoor")
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .body(JSONUtil.toJsonStr(data))
                .execute().body();
//        JSONObject resultJson = JSONUtil.parseObj(result);
//        if (resultJson.getStr("code").equals("200")) {
            return ResponseModel.success("开门成功");
//        } else {
//            return ResponseModel.fail(JSONUtil.parseObj(result).getStr("message"));
//        }
    }

    /**
     * 盘库操作(单个)
     */
    @PostMapping("/inventoryStorage")
    @ResponseBody
    public ResponseModel machineTurn(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("hostId"))) {
            return ResponseModel.fail("请选择柜号");
        }
        Host host = hostService.getById(data.getInt("hostId"));
        // 调用别的柜子接口
        String result = HttpRequest.post(host.getCabinetIp() + "/api/server/inventoryStorage")
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .body(JSONUtil.toJsonStr(data))
                .execute().body();
        JSONObject resultJson = JSONUtil.parseObj(result);
        if (resultJson.getStr("code").equals("200")) {
            return ResponseModel.success(JSONUtil.parseObj(result).getStr("message"));
        } else {
            return ResponseModel.fail(JSONUtil.parseObj(result).getStr("message"));
        }
    }

    /**
     * 电机正转
     */
    @GetMapping("forward")
    @ResponseBody
    public ResponseModel forward(@RequestParam(value = "action", required = true) String action, HttpServletRequest request) throws IOException {
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String number = getNumber(request);
        if ("start".equals(action)) {
            sendCmd.send("MOTORCCW:", request, null);
            motorLog(1, "用户 " + jwtUserDto.getUsername() + " 操作电机开始正转", jwtUserDto, number);
            return ResponseModel.success("电机正在上行，请注意安全");
        } else {
            sendCmd.send("MOTORSTOP:", request, null);
            motorLog(3, "用户 " + jwtUserDto.getUsername() + " 操作电机停止正转", jwtUserDto, number);
            return ResponseModel.success("电机已停止");
        }
    }

    /**
     * 电机反转
     */
    @GetMapping("reverse")
    @ResponseBody
    public ResponseModel reverse(@RequestParam(value = "action", required = true) String action, HttpServletRequest request) throws IOException {
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String number = getNumber(request);
        if ("start".equals(action)) {
            sendCmd.send("MOTORCW:", request, null);
            motorLog(2, "用户 " + jwtUserDto.getUsername() + " 操作电机开始反转", jwtUserDto, number);
            return ResponseModel.success("电机正在下行，请注意安全");
        } else {
            sendCmd.send("MOTORSTOP:", request, null);
            motorLog(3, "用户 " + jwtUserDto.getUsername() + " 操作电机停止反转", jwtUserDto, number);
            return ResponseModel.success("电机已停止");
        }
    }

    /**
     * 盘库
     */
    @GetMapping("inventory")
    @ResponseBody
    public ResponseModel inventory(HttpServletRequest request) throws IOException {
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sendCmd.send("SCANALL:", request, null);
        String number = getNumber(request);
        motorLog(6, "用户 " + jwtUserDto.getUsername() + " 开始盘库", jwtUserDto, number);
        return ResponseModel.success("盘库已开启");
    }

    /**
     * 开关门
     *
     * @param doorState
     * @return
     * @throws IOException
     */
    @GetMapping("door")
    @ResponseBody
    public ResponseModel door(@RequestParam(value = "doorState", required = true) String doorState, HttpServletRequest request) throws IOException {
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String number = getNumber(request);
        if ("true".equals(doorState)) {
            sendCmd.send("OPEN:", request, null);
            motorLog(4, "用户 " + jwtUserDto.getUsername() + " 开门", jwtUserDto, number);
            return ResponseModel.success("正在开门，请注意安全，将在15秒后完全打开");
        } else {
            sendCmd.send("CLOSE:", request, null);
            motorLog(5, "用户 " + jwtUserDto.getUsername() + " 关门", jwtUserDto, number);
            return ResponseModel.success("正在关门，请注意安全，将在15秒后完全关闭");
        }
    }

    /**
     * 读取并更新档案的ID号
     */
    @PostMapping("/current/layer/save")
    @ResponseBody
    public ResponseModel currentLayerSave(@RequestBody JSONObject data, HttpServletRequest request) throws IOException, InterruptedException {
        if (StrUtil.isEmpty(data.getStr("layerName"))) {
            return ResponseModel.fail("缺少层参数");
        }
        sendCmd.send("SCAN:" + data.getStr("layerName"), request, null);
        return ResponseModel.success("读取并更新档案的ID号");
    }


    /**
     * 选层操作
     */
    @PostMapping("/machine/turn")
    @ResponseBody
    public ResponseModel machineTurn(@RequestBody JSONObject data, HttpServletRequest request) {
        if (StrUtil.isEmpty(data.getStr("layer"))) {
            return ResponseModel.fail("缺少层参数");
        }
        sendCmd.send("TOANYLAYER:" + data.getStr("layer"), request, null);
        return ResponseModel.success("电机开始运行到 " + data.getStr("layer") + " 层");
    }
    /**
     * 选层操作停止
     */
    @PostMapping("/machine/stop")
    @ResponseBody
    public ResponseModel machineStop(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("MOTORSTOP:", request, null);
        return ResponseModel.success("电机已停止");
    }

    /**
     * 返回原点
     *
     * @param request
     * @return
     */
    @GetMapping("backToOrigin")
    @ResponseBody
    public ResponseModel backToOrigin(HttpServletRequest request) {
        sendCmd.send("BACKORIGIN:", request, null);
        return ResponseModel.success("电机返回原点成功");
    }


    /**
     * 门停止
     */
    @GetMapping("doorStop")
    @ResponseBody
    public ResponseModel doorStop(HttpServletRequest request) {
        sendCmd.send("STOP:", request, null);
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String number = getNumber(request);
        motorLog(7, "用户 " + jwtUserDto.getUsername() + " 操作门停止", jwtUserDto, number);
        return ResponseModel.success("正在操作门停止，请注意安全。");
    }

    /**
     * 故障复位
     */
    @GetMapping("faultReset")
    @ResponseBody
    public ResponseModel faultReset(HttpServletRequest request) {
        sendCmd.send("FAULTRST:", request, null);
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String number = getNumber(request);
        motorLog(8, "用户 " + jwtUserDto.getUsername() + " 操作故障复位", jwtUserDto, number);
        return ResponseModel.success("正在操作故障复位，请注意安全。");
    }


}
